package com.heima.article;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest
@RunWith(SpringRunner.class)
public class GeneratHtmlToMinio {

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;
    /**
     * 生成静态文件并上传到minio中
     * 公式=数据模型+静态模板=静态文件
     * 暂时是手动测试，等到完成了文章发布审核之后再集成当前方法
     */
    @Test
    public void uploadHtmlToMinio() throws Exception {
        //1.获取文章内容，根据文章id去查询
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(
                Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, 1302864436297482242L)
        );
        //2.获取模板
        Template template = configuration.getTemplate("article.ftl");
        //封装数据模型
        String content = apArticleContent.getContent();
        Map params=new HashMap<>();
        params.put("content", JSONArray.parseArray(content));

        //声明空的字符串写入流
        StringWriter stringWriter=new StringWriter();
        //3.生成静态html文件
        template.process(params,stringWriter);//相当于stringwriter流中就应该有了数据流

        //4.上传到minio中
        InputStream inputStream=new ByteArrayInputStream(stringWriter.toString().getBytes());
        String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", inputStream);
        //5.修改ap_article表中的static_url字段值
        ApArticle apArticle = apArticleMapper.selectById(apArticleContent.getArticleId());
        if(apArticle!=null){
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);
        }

    }
}
